<?php if(!defined('SPRITCH')) { exit(); }

// Spritch - An opensource PHP5 web framework

// Author: Luca Degasperi
// Licence: GNU GPL
// Site: http://www.spritch.org/

// Class: Storage
// Summary: This class provides cross page communications
// Since: 0.9.1

class storage extends spritch
{
	private $expiration = 0;
	private $storage_name = 'spritch_data';
	private $criptkey = '';
	private $now;
	private $data = array();
	
	public function __construct()
	{
		$this->now = time();
		
		if($this->expiration == 0)
			$this->expiration = (60*60*24*365);
			
		if(!$this->read())
			$this->create();
		$this->profiler->log('storage class started');
	}
	
	private function read()
	{
		$storage = $this->input->cookie($this->storage_name);
		if(!$storage)
			return false;
		
		$md5 = substr($storage,strlen($storage)-32);
		$storage = strtr($storage,'{s}','"');
		$storage = substr($storage,0,strlen($storage)-32);
		if(md5($storage.$this->criptkey) != $md5)
		{
			$this->profiler->warning('corrupred storage file');
			return !$this->destroy();
		}
		
		$storage = unserialize($storage);
		
		if(!is_array($storage) or !isset($storage['id']) or !isset($storage['ip_address']) or !isset($storage['activity']))
			return !$this->destroy();
		if($storage['ip_address'] != $this->input->ip_address())
			return !$this->destroy();
		if(($storage['activity'] + $this->expiration) < $this->now)
			return !$this->destroy();

		$this->data = $storage;
		return true;
	}
	
	private function set()
	{
		$data = serialize($this->data);				
		$md5 = md5($data.$this->criptkey);		
		$data = strtr($data,'"','{s}');		
		$data .= $md5;		
		setcookie ($this->storage_name, $data, (time()+$this->expiration), '/', '', false, true);
	}
	
	private function create()
	{
		$id = '';
		for($i = 0; $i < 32; $i++)
			$id .= mt_rand(0,9);
		$this->data = array
		(
			'id' => md5(uniqid($id,true)),
			'ip_address' => $this->input->ip_address(),
			'activity' => $this->now,
		);
		$this->set();
	}
	
	public function destroy()
	{
		setcookie($this->storage_name, serialize(array()), ($this->now - 31500000), '/', '', false, true);
		return true;
	}
	
	public function add($key,$value)
	{
		if(!array_key_exists($key,$this->data) or ($key != 'id' and $key != 'ip_address' and $key != 'activity'))
		{
			$this->data[$key] = $value;
			$this->set();
		}
	}
	
	public function remove($key)
	{
		if(array_key_exists($key,$this->data) and $key != 'id' and $key != 'ip_address' and $key != 'activity')
		{
			$this->data[$key] = null;
			$this->set();
		}
	}
	
	public function get($key = null,$default = null)
	{
		if(is_null($key))
			return $this->data;
		if(array_key_exists($key,$this->data))
			return $this->data[$key];
		if(is_null($default))
			return false;
		return $default;
	}
}
?>